--
-- @Author:      name
-- @DateTime:    2019-05-9 23:05:48
-- @Description: 消息处理

local skynet = require "skynet"
local log = require "Logger"

local MessageHandler = class("MessageHandler")

---------------------------------------------------------
-- Private
---------------------------------------------------------
function MessageHandler:ctor(message_dispatch, node_message, session_manager, user_manager)

    self.node_cluster_id = skynet.getenv("node_cluster_id")
    self.login_cluster_id = skynet.getenv("login_cluster_id")
	if self.login_cluster_id then 
		self.node_cluster_id = self.login_cluster_id
	end
	self.message_dispatch = message_dispatch
	self.node_message = node_message	
	self.session_manager = session_manager
	self.user_manager = user_manager

	self:register()
	-- skynet.fork(function()
	-- 	self:checkHeartLoop()
	-- end)
end

--注册本服务里的消息
function MessageHandler:register()

	self.message_dispatch:registerSelf('init',handler(self,self.init))
	self.message_dispatch:registerSelf('connect',handler(self,self.onConnect))
	self.message_dispatch:registerSelf('disconnect',handler(self,self.onDisconnect))

	
end

--包解析
function MessageHandler:messageUnpack(...)
	return self.node_message:unpackClient(...)
end

function MessageHandler:callNodeServer(user_id, message)
	if not user_id then 
		print("_________user_id错误_____")
		return 
	end
	local user_info = self.user_manager:getUserInfo(user_id)
	local command = message.command
	local des_server = nil --目标服务器
	return  self.node_message:callNodeProxy(self.node_cluster_id, "client_req", user_id, command.main_cmd_id, message)
end


--派发客户端消息，对返回消息处理
function MessageHandler:dispatchClientMessage(fd, address, message )
	skynet.ignoreret()	-- session is fd, don't call skynet.ret	
	if not message then
		self.node_message:sendPoxy('kick_session', fd)
		return
	end
	local session = self.session_manager:getSession(fd)	
	local command = message.command
	local res 
	if session  then 
		message.message_body.contype = session.contype
		message.message_body.session_id = session.session_id
	end
	if session and session.user_id then 
		message.message_body.user_id = session.user_id
	end	
	print("______command.main_cmd_id___",command.main_cmd_id, session, message)
	if command.main_cmd_id == 1001 then
		--loginserver
		res = self.node_message:callNodeProxy(self.node_cluster_id, "client_req", message)
	elseif command.main_cmd_id == 200 then
		--网关登录消息
		res = self.message_dispatch:dispatchSelfMessage(message.callback, message.message_body)
	else
		--透传到noderserver节点
		res = self:callNodeServer(session.user_id, message)
	end
	print("_______消息发往客户端_____",res)
	if type(res)=='table' and next(res) then 
		for message_name, body in pairs(res) do 
			self.node_message:sendClient(session.session_id, session.contype, message_name, body)
		end
	end
end

-- --心跳处理
-- function MessageHandler:checkHeartLoop()
-- 	while true do 
-- 		skynet.sleep(100)
-- 		local current_time = os.time() 
-- 		for k, v in pairs(self.session_manager:getSessionList()) do 
-- 			if current_time - v.time > 60 * 4 then --4分钟没收到包断开socket
-- 				v.time = current_time
-- 				print("#######240s没收到包###kick_player#########", v)			
-- 				self.node_message:sendService('.proxy', 'kick_user', v.session_id)		
-- 			end
-- 		end
-- 	end
-- end

------------------------------------------------------------------------------cmd----------
--初始化
function MessageHandler:init(pbc_env)	
	self.node_message:initProto(pbc_env)
end

--socket连入
function MessageHandler:onConnect(conf)

	local session = {
		session_id = conf.fd,    	--socket句柄
		contype = conf.contype,     --socket类型
		service = conf.service,     --socket服务 agent.lua
		addr = conf.addr,          	--ip地址
		time = os.time(),          	--计时器，长时间没反应删除socket
		sid = conf.sid or 1,        --消息验证id
		user_id = nil,       		--用户id
	}
	self.session_manager:addSession(session)

	--让agent.lua 把client消息转到这个服务来处理
	skynet.call(conf.service, "lua", "forward", conf.fd)
	print("MessageHandler:onConnect .........................")
end

--断线
function MessageHandler:onDisconnect(fd, msg, err)	
	local session = self.session_manager:getSession(fd)
	print("MessageHandler:onDisconnect .........................",session)
	if session then			
		local user_id = session.user_id
		if user_id then
			self.user_manager:removeUserInfo(user_id)			
		end
		self.session_manager:removeSession(fd)
		--通知断线
		self.node_message:callProxy('disconnect', fd, user_id)
		if user_id then
			--通知到游戏中
			local data = {
				server_type = "gameserver",	
				user_id = user_id,			
				message_name = "disconnect",
				message_body = {user_id = user_id,},
			}
			self.node_message:sendNodeProxy(self.node_cluster_id, "send_to_server", data)			
		end
	end
end



return MessageHandler